﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ReporterEngine.Methods
{
    public class UsedByReference : BaseMethod
    {
        public override bool IsUseable(LexPath.PathToken token)
        {
            return token.Kind == LexPath.TokenKind.UsedByReference && !string.IsNullOrEmpty(token.PathExp);
        }

        //prvok nemoze byt member a nesmie mat ani parenta member
        public override sQuery Execute(LexPath.PathToken token, sQuery query)
        {
            var result = query.New();

            var propertiesName = query.GetArgValuesForType(token);

            foreach (var element in query.Elements)
            {
                var id = query._model.GetID(element);

                if(query._model.REFs.ContainsKey(id.ToString()))
                {
                    var refs = query._model.REFs[id.ToString()];

                    foreach(var curRef in refs.Where(x=>x.Parent.Name.LocalName != "member"))
                    {
                        //test over all property names
                       foreach(var propertyName in propertiesName)
                       {
                           if(curRef.Name.LocalName.ToLower() == propertyName.ToLower())
                           {
                                result.Elements.Add(curRef.Parent);       
                           }
                       }
                    }
                }
            }

            result.Elements = result.Elements.Distinct(new CIFModel.NodeComparer()).ToList();
            result.Elements = result.Elements.OrderBy(x => query._model.GetElemenID(x, query)).ToList();

            return result;
        }

        public override MethodDescription[] GetMethodNames()
        {
            return new MethodDescription[]{new MethodDescription{IsUserMethod = false} };
        }
    }
}
